﻿namespace TestApp
{
    using System;
    using System.IO;
    using Newtonsoft.Json;

    internal sealed class JsonStorage : BaseStorage
    {
        public override T ReadFromKey<T>(string key)
        {
            try
            {
                using (var fs = storage.OpenFile(key, FileMode.OpenOrCreate))
                using (StreamReader sr = new StreamReader(fs))
                {
                    JsonSerializer s = new JsonSerializer();
                    return s.Deserialize<T>(new JsonTextReader(sr));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }

        public override void WriteWithKey(object obj, string key)
        {
            try
            {
                if (obj == null)
                {
                    return;
                }

                using (var fs = storage.CreateFile(key))
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    JsonSerializer s = new JsonSerializer();
                    s.Serialize(sw, obj);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }

        protected override string Extension
        {
            get { return "json"; }
        }
    }
}
